<?php
// +----------------------------------------------------------------------
// | RXThinkCMF敏捷开发框架 [ 赋能开发者，助力企业发展 ]
// +----------------------------------------------------------------------
// | 版权所有 2018~2023 南京RXThinkCMF研发中心
// +----------------------------------------------------------------------
// | Licensed LGPL-3.0 RXThinkCMF并不是自由软件，未经许可禁止去掉相关版权
// +----------------------------------------------------------------------
// | 官方网站: https://www.rxthink.cn
// +----------------------------------------------------------------------
// | Author: @牧羊人 团队荣誉出品
// +----------------------------------------------------------------------
// | 版权和免责声明:
// | 本团队对该软件框架产品拥有知识产权（包括但不限于商标权、专利权、著作权、商业秘密等）
// | 均受到相关法律法规的保护，任何个人、组织和单位不得在未经本团队书面授权的情况下对所授权
// | 软件框架产品本身申请相关的知识产权，禁止用于任何违法、侵害他人合法权益等恶意的行为，禁
// | 止用于任何违反我国法律法规的一切项目研发，任何个人、组织和单位用于项目研发而产生的任何
// | 意外、疏忽、合约毁坏、诽谤、版权或知识产权侵犯及其造成的损失 (包括但不限于直接、间接、
// | 附带或衍生的损失等)，本团队不承担任何法律责任，本软件框架禁止任何单位和个人、组织用于
// | 任何违法、侵害他人合法利益等恶意的行为，如有发现违规、违法的犯罪行为，本团队将无条件配
// | 合公安机关调查取证同时保留一切以法律手段起诉的权利，本软件框架只能用于公司和个人内部的
// | 法律所允许的合法合规的软件产品研发，详细声明内容请阅读《框架免责声明》附件；
// +----------------------------------------------------------------------

namespace app\admin\controller;
use think\Db;
use think\Request;
use app\admin\model\Member;
use app\admin\model\Project;
use app\admin\model\Task;
use app\admin\model\Match;
use app\admin\model\Standard;
use app\admin\model\Equipment;
use app\admin\model\Clss;
use app\admin\model\BraceletLog;
use app\admin\model\SportRecord;

use app\admin\service\LoginService;

/**
 * 同步数据-控制器
 * @author 牧羊人
 * @since 2020/11/19
 * Class Tongbu
 * @package app\admin\controller
 */
class Tongbu extends Backend
{
    /**
     * 初始化
     * @author 牧羊人
     * @since 2020/11/19
     */
    protected function initialize()
    {
        parent::initialize(); // TODO: Change the autogenerated stub
        $this->service = new LoginService();
    }

    /**
     * 同步年级班级记录
     * @return mixed
     * @since 2020/11/20
     * @author 牧羊人
     */
    public function tongbuGradeclass()
    {
        // 最近一天开始
        $startTime = strtotime('-1 day')*1000; // 将日期转换为毫秒时间戳
        //$startTime = strtotime('2023-11-09 00:00:00')*1000;
        // 当前时间
        $endTime = time()*1000; // 将日期和时间转换为毫秒时间戳
        //$endTime = strtotime('2023-11-09 23:59:59')*1000;
        $types = [1,2];//数据类型 1：校内体育测试 2：校内体育锻炼 3：校外体育云作业 4：校园云体锻
        $tbnum = 0;
        $data = [];
        foreach ($types as $v) {
                $datas = [
                    "type"=>$v, 
                    "startTimestamp"=> $startTime,
                    "endTimestamp"=> $endTime,
                    "pageNo"=> 1,
                    "pageSize"=> 100
                ];
            $result = $this->service->synchronousResult($datas);//获取第三方同步数据
            halt($result);
        }
        $match = new Match();
        $res = $match->where('begin_time','<=',strtotime('2024-10-08 16:34:58'))->where('end_time','>=',strtotime('2024-10-08 16:35:23'))->where('projectId',36)->where('mark',1)->find();
        var_dump($res);
    }
    //修复BMI为0的数据
    public function bim2()
    {
        cacl_bmi2();
    }
    //修复 仰卧起坐 坐位体前屈为0 的数据
    public function cacl()
    {

        //$map1[] = ['itemCode','=','weight'];
        $map1[] = ['projectId','in',[26,34]]; // 26 仰卧起坐 男 小于11 女小于 16 0 34 坐位体前屈
        //$map1[] = ['createdDate',['>','2024-10-7'],['<','2024-10-8']];;

        $list = SportRecord::where($map1)
            ->field('id,memberId,score,gender,pingscore,projectId,rating')
            ->whereNotNull('score')
            //->whereNull('bmi')
            ->where('pingscore=0')
            ->where('is_check=0')
            //->where('createdDate','<' ,'2024-10-25 19:37:51')
            ->where('createdDate','>' ,'2024-10-01 00:00:00')
            ->limit(100)
           //->where('id = 1051779')
            //->count();
            ->select();
        $count = SportRecord::where($map1)
            ->field('id,memberId,score,gender,pingscore,projectId,rating')
            ->whereNotNull('score')
            //->whereNull('bmi')
            ->where('pingscore=0')
            ->where('is_check=0')
            //->where('createdDate','<' ,'2024-10-25 19:37:51')
            ->where('createdDate','>' ,'2024-10-01 00:00:00')
            //->where('id = 1051779')
            //->count();
            ->count();
        echo '剩余数量'.$count;
        foreach($list as $vs){
            $standard = new Standard();
            $stanArr = json_decode($standard->where(['project'=>$vs['projectId']])->value('standard'),true);
            $pf = cacl_score26($stanArr,$vs);
            /*echo $vs['id'].'-projectId-'.$vs['projectId'].'-'.$vs['memberId'].'性别'.$vs['gender'].'分值'.$vs['score'].PHP_EOL;*/
            $pf['is_check'] = 1;
            //print_r($pf);
            trace('记录更新start');
            trace($vs['id'].'-'.$vs['memberId'].'性别'.$vs['gender'].'分值'.$vs['score']);
            trace($pf);
            trace('记录更新end');
            SportRecord::where('id',$vs['id'])->update($pf);
        }
    }

    public function caclscore()
    {
        $map1[] = ['is_check','=',0];
        $list = SportRecord::where($map1)
            ->field('id,memberId,score,gender,pingscore,projectId,rating')
            ->whereNotNull('score')
            //->whereNull('bmi')
            ->where('pingscore=0')
            //->where('is_check=0')
            //->where('createdDate','<' ,'2024-10-25 19:37:51')
            ->where('createdDate','>' ,'2024-10-01 00:00:00')
            ->limit(300)
            ->order('id desc')
            //->where('id = 1051779')
            //->count();
            ->select();
        foreach($list as $vs){
            $standard = new Standard();
            $s = $standard->where(['project'=>$vs['projectId']])->find();
            //$s = $standard->where(['project'=>$vs['projectId']])->value('standard');

            $stanArr = json_decode($s['standard'],true);
            $pf = cacl_score26($stanArr,$vs);
            /*echo $vs['id'].'-projectId-'.$vs['projectId'].'-'.$vs['memberId'].'性别'.$vs['gender'].'分值'.$vs['score'].PHP_EOL;*/
            $pf['is_check'] = 1;
            //print_r($pf);
            $s = $standard->where(['project'=>$vs['projectId']])->find();
            echo $s['name'];
            $str = $vs['id'].'-'.$vs['memberId'].'性别'.$vs['gender'].'分值'.$vs['score'].'成绩评分'.$pf['pingscore'].PHP_EOL;
            echo $str;
            /*trace('记录更新start');
            trace($str);
            trace($pf);
            trace('记录更新end');*/
            //SportRecord::where('id',$vs['id'])->update($pf);
        }
    }

    /**
     * 同步运动记录
     * @return mixed
     * @since 2020/11/20
     * @author 牧羊人
     */
    public function tongbuSport($start=null,$end=null)
    {
        // 最近一天开始
        $startTime = $start?strtotime($start)*1000:strtotime('-2 hours')*1000; // 将日期转换为毫秒时间戳
        //$startTime = strtotime('2023-11-09 00:00:00')*1000;
        // 当前时间
        $endTime = $end?strtotime($end)*1000:time()*1000; // 将日期和时间转换为毫秒时间戳
        //$endTime = strtotime('2023-11-09 23:59:59')*1000;
        $types = [1,2];//数据类型 1：校内体育测试 2：校内体育锻炼 3：校外体育云作业 4：校园云体锻
        $tbnum = 0;
        
        foreach ($types as $v) {

            $datas = [
                "type"=>$v, 
                "startTimestamp"=> $startTime,
                "endTimestamp"=> $endTime,
                "pageNo"=> 1,
                "pageSize"=> 1
            ];
            $result = $this->service->synchronousResult($datas);//获取第三方同步数据
            $total = isset($result['result']['total'])?intval($result['result']['total']):0;
            $batchSize = 500; // 每批次500条数据
            $batchCount = $total?ceil($total / $batchSize):0;
            $rows = [];
            for ($i = 1; $i < $batchCount; $i++) {
                $data = [];
                $datas = [
                    "type"=>$v, 
                    "startTimestamp"=> $startTime,
                    "endTimestamp"=> $endTime,
                    "pageNo"=> $i,
                    "pageSize"=> $batchSize
                ];
                $result = $this->service->synchronousResult($datas);//获取第三方同步数据
                $rows = isset($result['result']['rows'])?$result['result']['rows']:[];
                $clss = new Clss();
                $member = new Member();
                $project = new Project();
                $task = new Task();
                $match = new Match();
                $standard = new Standard();
                // $sdelarr = Db::name('sportrecord_del')->column('tbid');
                // Db::name('sportrecord_del')->where('tbid',$vs['id'])->value('tbid')
                foreach ($rows as &$vs) {
                    $tbtrue = Db::name('sportrecord_del')->where('tbid',$vs['id'])->value('tbid');
                    if (!$tbtrue) {
                        // code...
                    
                        $mlist = $member->where('roll',$vs['testerNumber'])->cache(300)->find();
                        if ($mlist) { //判断匹配学籍号
                            $vs['type'] = $v;
                            $vs['tbid'] = $vs['id'];
                            $vs['memberId'] = $mlist['id'];
                            $vs['schoolId'] = $mlist['organization'];
                            $vs['gradeId'] = $mlist['grade'];
                            $vs['classId'] = $mlist['class'];
                            $vs['departmentsId'] = $mlist['superior'];
                            $vs['tiyu_superior'] = $mlist['tiyu_superior'];
                            $vs['professionalId'] = $mlist['professional'];
                            $vs['tiyu_professional'] = $mlist['tiyu_professional'];
                            $vs['tiyu_class'] = $mlist['features']?intval(json_decode($mlist['features'],true)[0]):0;
                            $vs['tiyu_class_string'] = $mlist['features'];
                            $vs['projectId'] = $project->where(['organization'=>$vs['schoolId'],'code'=>$vs['itemCode'],'mark'=>1])->cache(105)->value('id');
                            if ($vs['itemCode']=='weight'||$vs['itemCode']=='height') {
                                $vs['projectId'] = $project->where(['organization'=>$vs['schoolId'],'code'=>'BMI','mark'=>1])->cache(115)->value('id');
                            }
                            $stanArr = [];
                            if ($v==1) {//体测数据
                                 $sta = $task->where('task_start','<=',$vs['startTime'])->where('task_end','>=',$vs['endTime'])->where('project',$vs['projectId'])->where('status',1)->where('mark',1)->find();
                                 
                                 if ($sta) {
                                     if ($sta['class']) {
                                            $vs['tiyu_class'] = 0;
                                            $clssarr = json_decode($sta['class'],true);
                                            foreach ($clssarr as $val) {
                                                $str = '"'.$vs['memberId'].'"';
                                                $df = $clss->where('id',intval($val))->where('features','like','%'
                                                    .$str.'%')->cache(125)->value('id');
                                                if ($df) {
                                                    $vs['tiyu_class'] = intval($val);
                                                    $vs['taskId'] = $sta['id']; //任务id
                                                }else{
                                                    $vs['tiyu_class'] = 0;
                                                    $vs['taskId'] = 0;
                                                }
                                            }  
                                     }
                                     $vs['model'] = $sta['model']; //任务模式
                                     $stanArr = json_decode($standard->where('id',$sta['standard'])->value('standard'),true);
                                 }else{
                                    $mat = $match->where('begin_time','<=',strtotime($vs['startTime']))->where('end_time','>=',strtotime($vs['endTime']))->where('projectId',$vs['projectId'])->where('mark',1)->find();
                                    if ($mat['mtype']==1) {
                                        $vs['type'] = 3; //体育赛事
                                    }

                                    if ($mat['mtype']==2) {
                                        $vs['type'] = 4; //院系测试
                                    }
                                    
                                    if ($mat) {
                                        $stanArr = json_decode($standard->where('project',$mat['projectId'])->cache
                                        (135)->value('standard'),true);
                                        $vs['taskId'] = $mat['id']; //赛事id
                                    }else{
                                        $vs['taskId']=0;
                                        $vs['type'] = 2; //体锻数据
                                        $pid = $project->where(['code'=>$vs['itemCode'],'mark'=>1])->cache
                                        (145)->value('id');
                                        if ($pid) {
                                            $stanArr = json_decode($standard->where(['organization'=>$vs['schoolId'],'project'=>$pid,'mark'=>1])->cache(155)->value('standard'),true);
                                        }

                                    }
                                 }
                            }
                            if ($v==2) {//体锻数据
                                $pid = $project->where(['code'=>$vs['itemCode'],'mark'=>1])->cache(165)->value('id');
                                if ($pid) {
                                    $stanArr = json_decode($standard->where(['organization'=>$vs['schoolId'],'project'=>$pid,'mark'=>1])->cache(175)->value('standard'),true);
                                }
                                
                            }
                            if ($stanArr) {
                                foreach ($stanArr as $vv) {
                                     if ($vv['sex']==$mlist['gender']) {
                                        switch ($vv['conditions']) {//判断成绩评级
                                            case 'gt':
                                                if ($vs['score']>$vv['target'][0]) {
                                                    $vs['rating'] = $vv['level'];
                                                    $vs['pingscore'] = $vv['score'];
                                                }
                                                break;
                                            case 'egt':
                                                if ($vs['score']>=$vv['target'][0]) {
                                                    $vs['rating'] = $vv['level'];
                                                    $vs['pingscore'] = $vv['score'];
                                                }
                                                break;
                                            case 'lt':
                                                if ($vs['score']<$vv['target'][0]) {
                                                    $vs['rating'] = $vv['level'];
                                                    $vs['pingscore'] = $vv['score'];
                                                }
                                                break;
                                            case 'elt':
                                                if ($vs['score']<=$vv['target'][0]) {
                                                    $vs['rating'] = $vv['level'];
                                                    $vs['pingscore'] = $vv['score'];
                                                }
                                                break;
                                            case 'between':
                                                if ($vs['score']>=$vv['target'][0]&&$vs['score']<=$vv['target'][1]) {
                                                    $vs['rating'] = $vv['level'];
                                                    $vs['pingscore'] = $vv['score'];
                                                }
                                                break;
                                            
                                            default:
                                                $vs['rating'] = 0;
                                                break;
                                        }
                                     }
                                 }
                            }
                            //归类统计
                            $vs['stype'] = $project->where(['organization'=>$vs['schoolId'],'code'=>$vs['itemCode']])
                                ->cache(140)->value('type');
                            $vs['gender'] = $vs['gender']=='M'?1:2;
                            if (isset($vs['videoUrlList'])) {
                                $vs['videoUrlList'] = json_encode($vs['videoUrlList']);
                            }
                            $data[] = $vs;
                        }
                    }else{
                        // echo $vs['id'].$vs['testerName'];
                    }
                }
                unset($vs);
                $sportrecord = new SportRecord();
                foreach ($data as $vv) {
                    $tbid = $vv['tbid'];
                    $id = $sportrecord->where('tbid',$tbid)->cache(150)->value('id');
                    if (!$id) {
                        $sportrecord->allowField(true)->insert($vv);
                    }else{
                        $up = $vv;
                        $sportrecord->allowField(true)->update($up);
                    }
                    $tbnum++;
                }
                unset($vv);
            }
            
        }
        
        //计算BMI结果
        cacl_bmi();
        echo "同步".$tbnum."条";
    }

    /**
     * 同步手环记录
     * @return mixed
     * @since 2020/11/20
     * @author 牧羊人
     */
    public function tongbuBracelet()
    {
        $class = new Clss();
        //查询开启手环体育班级
        $carr = $class->where(['mark'=>1,'stype'=>2,'braceletstatus'=>1])->cache(120)->select()->toArray();
        $member = new Member();
        $equipment = new Equipment();
        $bracelet = new BraceletLog();
        foreach ($carr as $val) {
            $startTime = $val['bracelet_start'];//手环开始时间
            $endTime = $val['bracelet_end']?$val['bracelet_end']:$startTime+(45*60);//手环结束时间
            $str = '"'.$val['id'].'"';
            $mw = [];
            $mw[] = ['features', 'like','%'.$str.'%'];
            //查询该体育班级的学员
            $mm = $member->where($mw)->select()->toArray();
            foreach ($mm as $val2) {
                $code = $equipment->where(['mark'=>1,'type'=>3,'use'=>1,'tagnumber'=>$val2['bracelet']])->value('code');
                $strjson = $this->curlBracelet($code,$startTime,$endTime);
                //查询学员手环记录表
                $bra = $bracelet->where(['memberId'=>$val2['id'],'clssId'=>$val['id'],'bracelet_time'=>date('Y-m-d H:i:s',$startTime)])->value('id');
                $strjson = json_decode($strjson,true);
                if ($strjson['data']) {
                    if ($bra) {
                        $bracelet->where(['memberId'=>$val2['id'],'clssId'=>$val['id'],'bracelet_time'=>date('Y-m-d H:i:s',$startTime)])->update(['json'=>json_encode($strjson['data']),'update_time'=>date('Y-m-d H:i:s')]);
                    }else{
                        $bracelet->insert(['memberId'=>$val2['id'],'clssId'=>$val['id'],'json'=>json_encode($strjson['data']),'bracelet_time'=>date('Y-m-d H:i:s',$startTime),'create_time'=>date('Y-m-d H:i:s'),'update_time'=>date('Y-m-d H:i:s')]);
                    }
                }
                
            }

            if ($endTime<=time()) {
                //超过45分钟关闭手环
                $class->where(['id'=>$val['id']])->update(['braceletstatus'=>0,'bracelet_end'=>time()]);
            }
            
        }
    }

    public function curlBracelet($deviceCode,$startTimeStr,$endTimeStr)
    {
        // 创建 cURL 句柄
        $curl = curl_init();

        // 设置 cURL 选项
        curl_setopt($curl, CURLOPT_URL, 'https://manage.cnshape.com/jty/lingkang/getDeviceOriginalData?deviceCode='.$deviceCode.'&startTimeStr='.$startTimeStr.'&endTimeStr='.$endTimeStr); // 设置请求的 URL
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); // 将返回的数据作为字符串返回，而不是直接输出到屏幕
        curl_setopt($curl, CURLOPT_HTTPHEADER,array("token: 64d5c597656243f9b0fa44e9c0e5e423456"));

        // 关闭SSL验证
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0);

        // 执行 cURL 请求
        $response = curl_exec($curl);
        // 关闭 cURL 句柄
        curl_close($curl);
        // 检查请求是否成功
        if ($response === false) {
            return 'cURL Error: ' . curl_error($curl);
        } else {
            // 处理返回的数据
            // halt($response);
            return $response;
        }

        
    }


    /**
     * 调用同步运动记录
     * @return mixed
     * @since 2020/11/20
     * @author 牧羊人
     */
    public function setongbuSport($start=null,$end=null)
    {
        // 最近一天开始
        $startTime = $start?strtotime($start)*1000:strtotime('-2 hours')*1000; // 将日期转换为毫秒时间戳
        //$startTime = strtotime('2023-11-09 00:00:00')*1000;
        // 当前时间
        $endTime = $end?strtotime($end)*1000:time()*1000; // 将日期和时间转换为毫秒时间戳
        //$endTime = strtotime('2023-11-09 23:59:59')*1000;
        $types = [1,2];//数据类型 1：校内体育测试 2：校内体育锻炼 3：校外体育云作业 4：校园云体锻
        $tbnum = 0;
        
        foreach ($types as $v) {

            $datas = [
                "type"=>$v, 
                "startTimestamp"=> $startTime,
                "endTimestamp"=> $endTime,
                "pageNo"=> 1,
                "pageSize"=> 500
            ];
            $result = $this->service->synchronousResult($datas);//获取第三方同步数据
            $total = isset($result['result']['total'])?intval($result['result']['total']):0;
            $rows = [];
                $data = [];
                $rows = isset($result['result']['rows'])?$result['result']['rows']:[];
                $clss = new Clss();
                $member = new Member();
                $project = new Project();
                $task = new Task();
                $match = new Match();
                $standard = new Standard();
                // $sdelarr = Db::name('sportrecord_del')->column('tbid');
                // Db::name('sportrecord_del')->where('tbid',$vs['id'])->value('tbid')
                foreach ($rows as &$vs) {
                    $tbtrue = Db::name('sportrecord_del')->where('tbid',$vs['id'])->value('tbid');
                    if (!$tbtrue) {
                        // code...
                    
                        $mlist = $member->where('roll',$vs['testerNumber'])->cache(300)->find();
                        if ($mlist) { //判断匹配学籍号
                            $vs['type'] = $v;
                            $vs['tbid'] = $vs['id'];
                            $vs['memberId'] = $mlist['id'];
                            $vs['schoolId'] = $mlist['organization'];
                            $vs['gradeId'] = $mlist['grade'];
                            $vs['classId'] = $mlist['class'];
                            $vs['departmentsId'] = $mlist['superior'];
                            $vs['tiyu_superior'] = $mlist['tiyu_superior'];
                            $vs['professionalId'] = $mlist['professional'];
                            $vs['tiyu_professional'] = $mlist['tiyu_professional'];
                            $vs['tiyu_class'] = $mlist['features']?intval(json_decode($mlist['features'],true)[0]):0;
                            $vs['tiyu_class_string'] = $mlist['features'];
                            $vs['projectId'] = $project->where(['organization'=>$vs['schoolId'],'code'=>$vs['itemCode'],'mark'=>1])->cache(105)->value('id');
                            if ($vs['itemCode']=='weight'||$vs['itemCode']=='height') {
                                $vs['projectId'] = $project->where(['organization'=>$vs['schoolId'],'code'=>'BMI','mark'=>1])->cache(115)->value('id');
                            }
                            $stanArr = [];
                            if ($v==1) {//体测数据
                                 $sta = $task->where('task_start','<=',$vs['startTime'])->where('task_end','>=',$vs['endTime'])->where('project',$vs['projectId'])->where('status',1)->where('mark',1)->find();
                                 
                                 if ($sta) {
                                     if ($sta['class']) {
                                            $vs['tiyu_class'] = 0;
                                            $clssarr = json_decode($sta['class'],true);
                                            foreach ($clssarr as $val) {
                                                $str = '"'.$vs['memberId'].'"';
                                                $df = $clss->where('id',intval($val))->where('features','like','%'
                                                    .$str.'%')->cache(125)->value('id');
                                                if ($df) {
                                                    $vs['tiyu_class'] = intval($val);
                                                    $vs['taskId'] = $sta['id']; //任务id
                                                }else{
                                                    $vs['tiyu_class'] = 0;
                                                    $vs['taskId'] = 0;
                                                }
                                            }  
                                     }
                                     $vs['model'] = $sta['model']; //任务模式
                                     $stanArr = json_decode($standard->where('id',$sta['standard'])->value('standard'),true);
                                 }else{
                                    $mat = $match->where('begin_time','<=',strtotime($vs['startTime']))->where('end_time','>=',strtotime($vs['endTime']))->where('projectId',$vs['projectId'])->where('mark',1)->find();
                                    if ($mat['mtype']==1) {
                                        $vs['type'] = 3; //体育赛事
                                    }

                                    if ($mat['mtype']==2) {
                                        $vs['type'] = 4; //院系测试
                                    }
                                    
                                    if ($mat) {
                                        $stanArr = json_decode($standard->where('project',$mat['projectId'])->cache
                                        (135)->value('standard'),true);
                                        $vs['taskId'] = $mat['id']; //赛事id
                                    }else{
                                        $vs['taskId']=0;
                                        $vs['type'] = 2; //体锻数据
                                        $pid = $project->where(['code'=>$vs['itemCode'],'mark'=>1])->cache
                                        (145)->value('id');
                                        if ($pid) {
                                            $stanArr = json_decode($standard->where(['organization'=>$vs['schoolId'],'project'=>$pid,'mark'=>1])->cache(155)->value('standard'),true);
                                        }

                                    }
                                 }
                            }
                            if ($v==2) {//体锻数据
                                $pid = $project->where(['code'=>$vs['itemCode'],'mark'=>1])->cache(165)->value('id');
                                if ($pid) {
                                    $stanArr = json_decode($standard->where(['organization'=>$vs['schoolId'],'project'=>$pid,'mark'=>1])->cache(175)->value('standard'),true);
                                }
                                
                            }
                            if ($stanArr) {
                                foreach ($stanArr as $vv) {
                                     if ($vv['sex']==$mlist['gender']) {
                                        switch ($vv['conditions']) {//判断成绩评级
                                            case 'gt':
                                                if ($vs['score']>$vv['target'][0]) {
                                                    $vs['rating'] = $vv['level'];
                                                    $vs['pingscore'] = $vv['score'];
                                                }
                                                break;
                                            case 'egt':
                                                if ($vs['score']>=$vv['target'][0]) {
                                                    $vs['rating'] = $vv['level'];
                                                    $vs['pingscore'] = $vv['score'];
                                                }
                                                break;
                                            case 'lt':
                                                if ($vs['score']<$vv['target'][0]) {
                                                    $vs['rating'] = $vv['level'];
                                                    $vs['pingscore'] = $vv['score'];
                                                }
                                                break;
                                            case 'elt':
                                                if ($vs['score']<=$vv['target'][0]) {
                                                    $vs['rating'] = $vv['level'];
                                                    $vs['pingscore'] = $vv['score'];
                                                }
                                                break;
                                            case 'between':
                                                if ($vs['score']>=$vv['target'][0]&&$vs['score']<=$vv['target'][1]) {
                                                    $vs['rating'] = $vv['level'];
                                                    $vs['pingscore'] = $vv['score'];
                                                }
                                                break;
                                            
                                            default:
                                                $vs['rating'] = 0;
                                                break;
                                        }
                                     }
                                 }
                            }
                            //归类统计
                            $vs['stype'] = $project->where(['organization'=>$vs['schoolId'],'code'=>$vs['itemCode']])
                                ->cache(140)->value('type');
                            $vs['gender'] = $vs['gender']=='M'?1:2;
                            if (isset($vs['videoUrlList'])) {
                                $vs['videoUrlList'] = json_encode($vs['videoUrlList']);
                            }
                            $data[] = $vs;
                        }
                    }else{
                        // echo $vs['id'].$vs['testerName'];
                    }
                }
                unset($vs);
                $sportrecord = new SportRecord();
                foreach ($data as $vv) {
                    $tbid = $vv['tbid'];
                    $id = $sportrecord->where('tbid',$tbid)->cache(150)->value('id');
                    if (!$id) {
                        $sportrecord->allowField(true)->insert($vv);
                    }else{
                        $up = $vv;
                        $sportrecord->allowField(true)->update($up);
                    }
                    $tbnum++;
                }
                unset($vv);
            
        }
        
        //计算BMI结果
        // cacl_bmi();
        return "同步".$tbnum."条";
    }

}